package system

import (
	"context"
	"strconv"
	"time"

	"portal/internal/errorx"
	"portal/internal/svc"
	"portal/internal/tool/auth"
	"portal/internal/types"
	"portal/model"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddMenuLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	menuModel model.SysMenuModel
}

func NewAddMenuLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddMenuLogic {
	return &AddMenuLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		menuModel: model.NewSysMenuModel(svcCtx.Orm),
	}
}

func (l *AddMenuLogic) AddMenu(req *types.AddMenuRequest) (resp *types.CommonResponse, err error) {
	err = auth.HasPermission(l.menuModel,l.ctx,"system:menu:add")
	if err != nil {
		return nil,errorx.Unauthorized
	}
	
	authinfo,err := auth.GetAuth(l.ctx)
	if err != nil {
		return nil,err
	}
	if len(req.ParentId) <= 0 {
		return nil,errorx.NewBizError(500,"父节点不能为空")
	}
	roleIds,_ := auth.GetRoleIds(l.ctx)
	parentId,err := strconv.Atoi(req.ParentId)
	if err != nil {
		return nil,errorx.TypeTransError
	}
	// 判断当前用户是否拥有对父节点的权限
	if isAdmin,_ := auth.IsAdmin(l.ctx); !isAdmin {
		err = l.menuModel.ExistByMIdRIds(l.ctx,nil,int64(parentId),roleIds)
		if err != nil {
			return nil,errorx.SqlExistError
		}
	}

	menu := &model.SysMenu{}
	err = insertValue(menu,&req.Menu)
	if err != nil {
		return nil,err
	}
	menu.CreateBy = authinfo.NickName
	menu.CreateTime = time.Now().Unix()
	menu.UpdateBy = authinfo.NickName
	menu.UpdateTime = time.Now().Unix()
	menuId,err := l.menuModel.InsertGetId(l.ctx,nil,menu)
	if err != nil {
		return nil,errorx.SqlInsertError
	}
	return &types.CommonResponse{
		Status: 200,
		Msg: "修改成功",
		Data: types.IdResponse{
			Id: menuId,
		},
	},err
}

func insertValue(origin *model.SysMenu,now *types.Menu)error{
	parentId,err := strconv.Atoi(now.ParentId)
	if err != nil {
		return err
	}
	if len(now.ParentId) > 0 && int64(parentId) != origin.ParentId { 
		origin.ParentId = int64(parentId)
	}
	if len(now.MenuName) <= 0 {
		return errorx.NewBizError(500,"菜单名称不能为空")
	}
	origin.MenuName = now.MenuName
	if now.OrderNum <= 0 {
		return errorx.NewBizError(500,"显示排序不能为空")
	}
	origin.OrderNum = now.OrderNum
	if len(now.Path) <= 0{
		return errorx.NewBizError(500,"路由地址不能为空")
	} 
	origin.Path = now.Path
	if len(now.Component) > 0{
		origin.Component.String = now.Component
		origin.Component.Valid = true
	} 
	if len(now.Query) > 0 {
		origin.Query.String = now.Query
		origin.Query.Valid = true
	}
	if len(now.MenuType) > 0 {
		origin.MenuType = now.MenuType
	}
	if len(now.Visible) > 0 {
		origin.Visible = now.Visible
	}
	if len(now.Status) > 0 {
		origin.Status = now.Status
	}
	if len(now.Perms) > 0 {
		origin.Perms.String = now.Perms
		origin.Perms.Valid = true
	}
	if len(now.Icon) > 0 {
		origin.Icon = now.Icon
	}
	return nil
}

